﻿using AndroidXml;
using Newtonsoft.Json.Linq;
using QD.LopPlat.UI.Code;
using QD.LopPlat.UI.Code.DbContent;
using QD.UpDownLoad;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace QD.LopPlat.UI
{
    public partial class AppSetting : Form
    {
        string _filePath = "";
        int _id = 0;//0为新增，其他为编辑
        public AppSetting()
        {
            InitializeComponent();
        }

        private void AppSetting_Load(object sender, EventArgs e)
        {
            this.label2.Text = "";
            this.label8.Text = "";
            this.label7.Text = "";
            this.textBox2.Text = WebClientHelper.ServerUri;

            DbQfDevPlat db = new DbQfDevPlat();
            DataTable dt = db.Query("select * from App_Setting");
            if (dt != null && dt.Rows.Count > 0)
            {
                _id = int.Parse(dt.Rows[0]["ID"].ToString());
                this.label2.Text = dt.Rows[0]["NewVersion"].ToString();
                this.label7.Text = dt.Rows[0]["FielName"].ToString();
                this.textBox2.Text = dt.Rows[0]["DownLoadPath"].ToString();
                this.richTextBox1.Text = dt.Rows[0]["Explain"].ToString();
                this.textBox1.Text = dt.Rows[0]["SavePath"].ToString();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.textBox2.Text))
                {
                    MessageBox.Show("下载地址不能为空！");
                    this.textBox2.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.textBox1.Text))
                {
                    MessageBox.Show("保存路径不能为空！");
                    this.textBox1.Focus();
                    return;
                }

                if (_id == 0) //新增
                {
                    if (string.IsNullOrEmpty(this.label8.Text))
                    {
                        MessageBox.Show("请先上传App安装包！");
                        return;
                    }
                    if (string.IsNullOrEmpty(this.label7.Text))
                    {
                        MessageBox.Show("文件名不能为空！");
                        return;
                    }

                    if (uploadFiles())
                    {
                        DbQfDevPlat db = new DbQfDevPlat();
                        string sql = string.Format("INSERT INTO App_Setting (OriVersion,NewVersion,FielName,DownLoadPath,LastUpDate,LastUpCoder,LastUpCoderName,Explain,SavePath) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')",
                               this.label2.Text.Trim(), this.label8.Text.Trim(), this.label7.Text, this.textBox2.Text.Trim(), DateTime.Now, QDUserHelper.LoginQdUser.Uid, QDUserHelper.LoginQdUser.UName, this.richTextBox1.Text.Trim(), this.textBox1.Text.Trim());
                        db.ExecuteNonQuery("delete App_Setting");
                        db.ExecuteNonQuery(sql);
                        MessageBox.Show("保存成功！");
                        AppSetting_Load(null, null);
                    }
                }
                else//编辑
                {
                    if (string.IsNullOrEmpty(this.label8.Text))//不上传APP
                    {
                        DbQfDevPlat db = new DbQfDevPlat();
                        string sql = string.Format("UPDATE App_Setting SET DownLoadPath = '{0}',Explain='{1}',SavePath='{2}' WHERE ID = {3}", this.textBox2.Text.Trim(), this.richTextBox1.Text.Trim(), this.textBox1.Text.Trim(), _id);
                        db.ExecuteNonQuery(sql);
                        MessageBox.Show("保存成功！");
                        AppSetting_Load(null, null);
                    }
                    else
                    {
                        if (uploadFiles())
                        {
                            DbQfDevPlat db = new DbQfDevPlat();
                            string sql = string.Format("INSERT INTO App_Setting (OriVersion,NewVersion,FielName,DownLoadPath,LastUpDate,LastUpCoder,LastUpCoderName,Explain,SavePath) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')",
                                this.label2.Text.Trim(), this.label8.Text.Trim(), this.label7.Text, this.textBox2.Text.Trim(), DateTime.Now, QDUserHelper.LoginQdUser.Uid, QDUserHelper.LoginQdUser.UName, this.richTextBox1.Text.Trim(), this.textBox1.Text.Trim());
                            db.ExecuteNonQuery("delete App_Setting");
                            db.ExecuteNonQuery(sql);
                            MessageBox.Show("保存成功！");
                            AppSetting_Load(null, null);
                        }
                    }
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void pl_autoup_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Filter = "文件格式|*.apk";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string fileName = dialog.FileName;
                    _filePath = fileName;
                    string version = GetVersion(fileName);
                    this.label7.Text = "install_" + version + ".apk";
                    this.label8.Text = version;
                }
            }
            catch (Exception ex)
            {
                Tools.PromptHelper.Prompt(ex.Message);
            }
        }
        private bool uploadFiles()
        {
            if (!string.IsNullOrEmpty(_filePath))
            {
                string dowPath = this.textBox1.Text.Trim();
                if (string.IsNullOrEmpty(dowPath))
                {
                    Tools.PromptHelper.Prompt("请设置保存路径！");
                    return false;
                }
                string loadVer = this.label2.Text;
                if (string.IsNullOrEmpty(this.label2.Text))
                {
                    loadVer = "1.0";
                }
                string version = this.label8.Text;
                Version now_v = new Version(version);
                Version load_v = new Version(loadVer);
                if (!string.IsNullOrEmpty(this.label2.Text) && now_v <= load_v)
                {
                    Tools.PromptHelper.Prompt("当前上传的版本过低，请上传新版本！");
                    return false;
                }
                UpLoadFile(_filePath, dowPath, version, this.textBox2.Text.Trim());
                return true;
            }
            return false;
        }
        private void pl_autoup_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                string filePath = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                string exName = System.IO.Path.GetExtension(filePath); //得到扩展名
                if (exName.ToUpper() == ".APK")
                {
                    _filePath = filePath;
                    string version = GetVersion(filePath);
                    this.label7.Text = "install_" + version + ".apk";
                    this.label8.Text = version;
                }
                else
                {
                    Tools.PromptHelper.Prompt("请上传apk文件！");
                }
            }
            catch (Exception ex)
            {
                Tools.PromptHelper.Prompt(ex.Message);
            }
        }
        /// <summary>
        /// 获取apk版本号
        /// </summary>
        /// <param name="filePath">apk路径</param>
        /// <returns></returns>
        private string GetVersion(string filePath)
        {
            string version = "";
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)))//这里的后面连哥哥参数很重要哦，不然很有可能出现独占
            {
                using (var filestream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))//这里的后面连哥哥参数很重要哦，不然很有可能出现独占

                {
                    using (ICSharpCode.SharpZipLib.Zip.ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream))
                    {
                        ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                        string content = string.Empty;
                        while ((item = zip.GetNextEntry()) != null)
                        {
                            if (item.Name == "AndroidManifest.xml")
                            {
                                byte[] bytes = new byte[50 * 1024];

                                using (Stream strm = zipfile.GetInputStream(item))
                                {
                                    int size = strm.Read(bytes, 0, bytes.Length);

                                    using (BinaryReader s = new BinaryReader(strm))
                                    {
                                        byte[] bytes2 = new byte[size];
                                        Array.Copy(bytes, bytes2, size);
                                        //AndroidXml. decompress = new AndroidDecompress();
                                        List<AndroidInfo> androidInfos = new List<AndroidInfo>();
                                        #region 读取文件内容
                                        using (var stream = new MemoryStream(bytes))
                                        {
                                            var reader = new AndroidXmlReader(stream);

                                            while (reader.Read())
                                            {
                                                switch (reader.NodeType)
                                                {
                                                    case XmlNodeType.Element:
                                                        {
                                                            AndroidInfo info = new AndroidInfo();
                                                            androidInfos.Add(info);
                                                            info.Name = reader.Name;
                                                            info.Settings = new List<AndroidSetting>();
                                                            for (int i = 0; i < reader.AttributeCount; i++)
                                                            {
                                                                reader.MoveToAttribute(i);
                                                                if (reader.Name == "android:versionCode")
                                                                {
                                                                    version += reader.Value;
                                                                }
                                                                if (reader.Name == "android:versionName")
                                                                {
                                                                    version = reader.Value + "." + version;
                                                                }
                                                                AndroidSetting setting = new AndroidSetting() { Name = reader.Name, Value = reader.Value };
                                                                info.Settings.Add(setting);
                                                            }
                                                            return version;
                                                            //reader.MoveToElement();
                                                            //break;
                                                        }
                                                }
                                            }

                                        }

                                        #endregion
                                    }

                                }
                            }

                        }

                    }

                }
            }
            return version;
        }
        /// <summary>
        /// android应用程序信息
        /// </summary>
        public class AndroidInfo
        {
            public string Name { get; set; }

            public List<AndroidSetting> Settings { get; set; }
        }

        /// <summary>
        /// 设置
        /// </summary>
        public class AndroidSetting
        {
            public string Name { get; set; }
            public string Value { get; set; }
        }
        private void pl_autoup_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
        private static string UpLoadFile(string filePath, string dowPath, string version, string url)
        {
            System.Net.WebClient myWebClient = new System.Net.WebClient();
            //上传的链接地址（文件服务器）
            Uri _uri = new Uri(url + "/api/FileUpload/PostApkUpload?UploadFile=" + dowPath + "&version=" + version);
            //上传文件到服务器
            byte[] b = myWebClient.UploadFile(_uri, "POST", filePath);
            string strJson = System.Text.Encoding.Default.GetString(b);
            JObject jObj = JObject.Parse(strJson);
            if (jObj["success"].ToString() == "False")
            {
                new Exception("上传失败：" + jObj["error"].ToString());
            }
            return "";
        }
    }
}
